package com.richpencil.modules.weixin.service.impl;

import com.google.common.primitives.Ints;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.api.SnsAccessToken;
import com.jfinal.weixin.sdk.api.SnsAccessTokenApi;
import com.jfinal.weixin.sdk.api.SnsApi;
import com.richpencil.config.ProjectConfigInfo;
import com.richpencil.config.datasource.BaseService;
import com.richpencil.modules.weixin.domain.*;
import com.richpencil.modules.weixin.service.WxService;
import com.richpencil.utils.LongHelper;
import com.richpencil.utils.StringHelper;
import com.richpencil.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class WxServiceImpl extends BaseService implements WxService {

    @Autowired
    com.richpencil.modules.weixin.repository.WaswxmpconfigRepository WaswxmpconfigRepository;

    public WaswxmpConfig getDefaultOne() throws Exception {

       return null;
    }
    public void updateDefaultOne(){

    }


    @Autowired
    public ProjectConfigInfo projection;

    public String encodeVueUrl(String fconfigid, SysEnum e, String fid){

        StringBuilder builder=new StringBuilder();
        builder.append(projection.authorizeurl);
        builder.append(e.url);
        builder.append("?fconfigid=");
        builder.append(fconfigid);
        builder.append("&fsysid=");
        builder.append(e.fsysid);
        builder.append("&fid=");
        builder.append(fid);
        return builder.toString();

    }

    public String encodeWeixinAuthUrl(String fconfigid,String fsysid,String fid){

        StringBuilder builder=new StringBuilder();
        builder.append(projection.authorizeurl);
        builder.append("?fconfigid=");
        builder.append(fconfigid);
        builder.append("&fsysid=");
        builder.append(fsysid);
        builder.append("&fid=");
        builder.append(fid);
        return builder.toString();

    }


    public String encodeState(String fconfigid,String ftype,String fid){
        return fconfigid+"@"+ftype+"@"+fid;
    }

    public UrlEntry decodeState(String state){


        UrlEntry entry=new UrlEntry();
        if(StringHelper.IsEmptyOrNull(state)){
            entry.success=false;
            return entry;
        }
        String[] ary=state.split("@");
        if(ary.length<2){
            entry.success=false;
            return entry;
        }
        entry.fconfigid=ary[0];
        entry.ftype= Ints.tryParse(ary[1]);
        entry.fid=ary[1];
        return entry;
    }

    public String getVueUrl(UrlEntry entry){
        SysEnum e=SysEnum.findOne(entry.ftype);
        String url=e.url+"?fopenid="+entry.fopenid+"&ftype="+entry.ftype;


        //this.encodeServerUrl(entry.fconfigid,entry.ftype.toString(), entry.fid);
        return url;
    }




    @Autowired
    public ProjectConfigInfo projectInfo;
    public WxResult getWxResult(String WxCode, String ip)
    {
        SnsAccessToken snsAccessToken = SnsAccessTokenApi.getSnsAccessToken(this.projectInfo.appid, this.projectInfo.appsecrect, WxCode);
        WxResult wxresult = this.getWxResult(snsAccessToken, ip);
        return wxresult;
    }
    public WxResult getWxResult(SnsAccessToken snsAccessToken, String ip) {
        WxResult wr = new WxResult();
        if (snsAccessToken.getErrorCode() == null) {
            String openid = snsAccessToken.getOpenid();
            String token = snsAccessToken.getAccessToken();
            ApiResult apiResult = SnsApi.getUserInfo(token, openid);
            if (apiResult == null) {
                wr.message = "apiResult is null";
                wr.success = false;
            }
            if (apiResult.getErrorCode() == null) {
                String nickname = apiResult.getStr("nickname");
                String logoimg = apiResult.getStr("headimgurl");
                wr.logoimg = logoimg;
                wr.nickname = nickname;
                wr.openid = openid;
                wr.success = true;
            } else {
                wr.message = "[apiResult Error Msg]" + apiResult.getErrorMsg() + "[error code]"
                        + apiResult.getErrorCode();
                wr.success = false;
            }
        } else {
            wr.message = "[snsAccessToken Error Msg]" + snsAccessToken.getErrorMsg() + "[error code]"
                    + snsAccessToken.getErrorCode();
            wr.success = false;
        }
        return wr;

    }
    public CreateUserInstance spCreateWxUser(WxResult wxresult, String factionid, String fuseridiv) {
        CreateUserInstance instance = new CreateUserInstance();
        long l_fuseridiv = 0;
        try {
            if(!StringUtils.isEmpty(fuseridiv)) {
                l_fuseridiv = Long.parseLong(fuseridiv);
            } else {
                l_fuseridiv = 0;
            }
        } catch (Exception ex) {
        }
        instance.p_factionid = factionid;
        instance.p_fopenid = wxresult.openid;
        instance.p_flogoimg = wxresult.logoimg;
        instance.p_nickname = wxresult.nickname;
        instance.p_useridiv = l_fuseridiv;
        instance.ret = -1;
        //this.WxActionUserMapper.sp_createWxUser(instance);
        return instance;
    }
    public String getViewFrontUrl(String factionid,long fuserid,long fuseridiv)
    {
        String fronturl = this.projectInfo.vueurl;
        String vueurl = "redirect:" + fronturl + "/?factionid=" + factionid
                + "&fuserid=" + String.valueOf(fuserid)
                + "&fuseridiv=" + String.valueOf(fuseridiv)
                + "&t=" + System.currentTimeMillis();
        return vueurl;
    }
    @Override
    public queryFrontInstance queryFrontUrl(String factionid, String fuseridiv, String wxcode, String ip) {
        queryFrontInstance qv=new queryFrontInstance();
        String url = "/wx/result";
        WxResult wxresult = this.getWxResult(wxcode,ip);
        String vueurl = "";
        if (wxresult.success) {
            CreateUserInstance instance  = this.spCreateWxUser(wxresult, factionid, fuseridiv);
            qv.ret=instance.ret;
            long l_fuseridiv_owner= LongHelper.TryParse(fuseridiv);
            long l_fuserid=instance.p_fuserid;
            long l_fuseridiv=instance.p_useridiv;
            if(l_fuseridiv_owner==l_fuserid) {

                vueurl=this.getViewFrontUrl(factionid,l_fuserid,l_fuserid);
            } else {

                vueurl=this.getViewFrontUrl(factionid,l_fuserid,l_fuseridiv);
            }
            qv.vueurl=vueurl;
            qv.success=true;

        } else {

            qv.vueurl = url;
            qv.success=false;
        }
        return qv;
    }

    @Override
    public void createWxUser() {

    }
}
